package com.qf.controller;

import com.alibaba.druid.util.StringUtils;
import com.qf.annotations.RequestMapping;
import com.qf.converts.MyDateConvert;
import com.qf.pojo.PageBean;
import com.qf.pojo.TbGoods;
import com.qf.pojo.TbGoodsKz;
import com.qf.service.GoodsService;
import com.qf.service.Impl.GoodsServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import javax.annotation.Resource;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

@RequestMapping("/goods")
public class GoodsServlet {
    @Resource
    private GoodsService goodsService;

    @RequestMapping("/add")
    private String addGoods(HttpServletRequest request, HttpServletResponse response) throws Exception {
        TbGoodsKz tbGoodsKz = new TbGoodsKz();
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
        List<FileItem> items = servletFileUpload.parseRequest(request);

        List<FileItem> picture = items.stream().filter(item -> {
            return item.getFieldName().equals("picture");//进行过滤,返回 true 的数据将会被保留,我们保留的是非图片的数据
        }).collect(Collectors.toList());
        if (picture == null || picture.size() == 0) {
            response.setContentType("text/html;charset=utf-8");

            return "没有传递图片";
        }
        String realPath = request.getServletContext().getRealPath("/pic/");
        System.err.println("获取到的图片路径" + realPath);
        File file = new File(realPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        String fileName = UUID.randomUUID().toString().replaceAll("-", "");
        String uploadFileName = picture.get(0).getName();
        System.out.println("名字" + uploadFileName);
        fileName = fileName + uploadFileName.substring(uploadFileName.lastIndexOf("."));
        System.err.println("新名字" + fileName);
        IOUtils.copy(picture.get(0).getInputStream(), new FileOutputStream(realPath + fileName));
        String savePath = "/pic/" + fileName;

        Map<String, String> map = items.stream().filter(item -> {
            return !item.getFieldName().equals("picture");
        }).collect(Collectors.toMap(FileItem::getFieldName, fileItem -> {
            try {
                return fileItem.getString("utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return null;
        }));

        List<FileItem> priceList = items.stream().filter(item -> {
            return item.getFieldName().equals("price");//进行过滤,返回 true 的数据将会被保留,我们保留的是非图片的数据
        }).collect(Collectors.toList());

        double priceDouble = Double.parseDouble(priceList.get(0).getString());


        ConvertUtils.register(new MyDateConvert(), Date.class);
        BeanUtils.populate(tbGoodsKz, map);
        tbGoodsKz.setPrice((long) (priceDouble * 100));
        tbGoodsKz.setPicture(savePath);
        System.out.println("封装后的数据" + tbGoodsKz);

        goodsService.addGoods(tbGoodsKz);
        return "redirect:/admin/success.jsp";
    }

    @RequestMapping("/show")
    public String show(HttpServletRequest request, HttpServletResponse response) {
        //查询数据,保存到 request中
        String id = request.getParameter("id");//分类 id
        String currentPage = request.getParameter("currentPage");//当前页码
        int currentPageNum = 1;//默认是第一页
        int typeId = Integer.parseInt(id);//将分类 id 转换为 int

        if (currentPage != null && !"".equalsIgnoreCase(currentPage.trim())) {
            currentPageNum = Integer.parseInt(currentPage);//传递了当前页的时候使用当前页
        }

        try {
            PageBean<TbGoods> pageBean = goodsService.getGoodsPageByTypeId(typeId, currentPageNum);
            request.setAttribute("pageBean", pageBean);//保存了数据,跳转页面
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "forward:/goodsList.jsp";
    }

    @RequestMapping("/detail")
    public String detail(HttpServletRequest request, HttpServletResponse response) {
        //查询数据,保存到 request中
        String id = request.getParameter("id");//分类 id
        if (StringUtils.isEmpty(id)) {
            return "redirect:/error/error.jsp";
        }
        TbGoods tbGoods = goodsService.getGoodById(Integer.parseInt(id));
        request.setAttribute("product", tbGoods);
        return "forward:/goodsDetail.jsp";

    }
}
